package com.atguigu.service_edu.service.impl;

import com.atguigu.service_edu.entity.EduChapter;
import com.atguigu.service_edu.entity.EduVideo;
import com.atguigu.service_edu.entity.chapter.ChapterVo;
import com.atguigu.service_edu.entity.chapter.VideoVo;
import com.atguigu.service_edu.mapper.EduChapterMapper;
import com.atguigu.service_edu.service.EduChapterService;
import com.atguigu.service_edu.service.EduVideoService;
import com.atguigu.servicebase.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author clark
 * @since 2020-04-10
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService eduVideoService;


    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        List<ChapterVo> chapterVoList = new ArrayList<>();

        //根据课程ID获取章节集合
        QueryWrapper<EduChapter> wrapperChapter = new QueryWrapper<>();
        wrapperChapter.eq("course_id",courseId);
        List<EduChapter> chapterList = baseMapper.selectList(wrapperChapter);
        //遍历章节集合
        chapterList.forEach(eduChapter -> {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            //根据章节ID获取视频集合
            QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
            wrapperVideo.eq("chapter_id",eduChapter.getId());
            List<EduVideo> eduVideoList = eduVideoService.list(wrapperVideo);
            //遍历视频集合
            eduVideoList.forEach(eduVideo -> {
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(eduVideo,videoVo);
                chapterVo.getChildren().add(videoVo);
            });
            chapterVoList.add(chapterVo);
        });
        return chapterVoList;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("chapter_id",chapterId);
        int count = eduVideoService.count(wrapperVideo);
        if(count > 0){
            throw new GuliException(20001,"不能删除");
        }else{
            int i = baseMapper.deleteById(chapterId);
            return i > 0 ;
        }
    }

    @Override
    public void removeByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }
}
